import 'package:family_expense/features/system_setting/services/app_release_log_service.dart';
import 'package:family_expense/features/system_setting/widgets/app_update_info.dart';
import 'package:family_expense/features/system_setting/widgets/change_log.dart';
import 'package:flutter/material.dart';
import 'package:my_flutter_core/my_flutter_core.dart';
import 'package:qr_flutter/qr_flutter.dart';

class AboutView extends StatefulWidget {
  const AboutView({super.key});

  @override
  State<AboutView> createState() => _AboutViewState();
}

class _AboutViewState extends State<AboutView> {
  final AppReleaseLogService _appReleaseLogService = AppReleaseLogService();

  AppInfo? _appInfo;
  CheckAppUpdateResult? _checkUpdateResult;
  String? _appVersion;

  @override
  void initState() {
    super.initState();

    _queryAppInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: _buildAppBar(), body: _buildBody());
  }

  /// Builds app bar.
  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      leading: IconButton(
        icon: const Icon(Icons.arrow_back, color: Colors.grey),
        onPressed: () => NavigatorHelper.pop(context),
      ),
      backgroundColor: const Color.fromRGBO(250, 250, 250, 1.0),
      elevation: 0.0,
    );
  }

  /// Builds main body.
  Widget _buildBody() {
    return ListView(
      children: [
        SizedBox(
          height: 260.0,
          child: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset('assets/images/logo.png', width: 80.0),
                const SizedBox(height: 10.0),
                Text(
                  'Family Expense',
                  style: Theme.of(context).textTheme.titleLarge,
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 20.0),
                Text(_appVersion != null ? 'v$_appVersion' : '读取版本号'),
                Text(
                  _appInfo != null
                      ? _appInfo!.releaseDate.formatDate(DatePatterns.longDate)
                      : '获取发布日期',
                ),
              ],
            ),
          ),
        ),
        // Downloading apk file for upgrade is for Android ONLY.
        if (PlatformInfo.isAndroid)
          Column(
            children: [
              const Divider(),
              SimpleDetailListTile(
                title: Text(
                  _checkUpdateResult?.hasUpdate == true ? '查看版本更新' : '无更新版本',
                ),
                value: _checkUpdateResult?.hasUpdate == true
                    ? Chip(
                        padding: const EdgeInsets.all(0.0),
                        label: Text(
                          'v${_checkUpdateResult!.appInfo!.appVersion}',
                        ),
                        backgroundColor: Colors.lightGreenAccent,
                      )
                    : Container(),
                onTap: () {
                  if (_checkUpdateResult?.hasUpdate == true) {
                    NavigatorHelper.push(
                      context,
                      AppUpdateInfo(_checkUpdateResult!),
                    );
                  } else {
                    showToast('当前无更新版本');
                  }
                },
              ),
              SimpleDetailListTile(
                title: const Text('更新日志'),
                onTap: () => NavigatorHelper.push(context, const ChangeLog()),
              ),
              SimpleDetailListTile(
                title: const Text('分享APP'),
                onTap: _showQrCode,
              ),
            ],
          ),
      ],
    );
  }

  /// Queries the current app info details by version.
  Future<void> _queryAppInfo() async {
    // Gets app current version.
    final appVersion = await getAppLocalVersion();

    // Triggers the build.
    if (mounted) {
      setState(() => _appVersion = appVersion);
    }

    // Checks update.
    _checkUpdate(appVersion);

    // Queries current version details.
    final appInfo = await _appReleaseLogService.queryByAppVersion(appVersion);

    // Triggers the build.
    if (mounted && appInfo != null) {
      setState(() => _appInfo = appInfo);
    }
  }

  /// Checks the app update info.
  Future<void> _checkUpdate(String appVersion) async {
    final checkUpdateResult = await _appReleaseLogService.checkUpdate(
      appVersion,
    );

    if (mounted) {
      setState(() => _checkUpdateResult = checkUpdateResult);
    }
  }

  /// Shows a QR code to share current app downloading url.
  void _showQrCode() {
    showDialog(
      context: context,
      builder: (context) {
        return SimpleDialog(
          title: const Text('扫码下载', textAlign: TextAlign.center),
          children: [
            Center(
              child: _checkUpdateResult != null
                  ? Container(
                      margin: const EdgeInsets.only(bottom: 10.0),
                      width: 200.0,
                      child: QrImageView(
                        data: _checkUpdateResult!.sharingH5Url!,
                      ),
                    )
                  : const Text('正在获取app信息'),
            ),
          ],
        );
      },
    );
  }
}
